package com.kssoft.ebd.spider.test;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import cn.hutool.core.thread.ThreadUtil;
import com.kssoft.ebd.spider.common.CommonUtils;
import com.kssoft.ebd.spider.common.NullCookiesException;
import com.kssoft.ebd.spider.downloader.HttpClientDownloader;
import com.kssoft.ebd.spider.pool.WebDriverPool;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;

@Component
public class Anyue implements PageProcessor {

    @Autowired
    private WebDriverPool webDriverPool;

    //log
    private static final Logger logger = LoggerFactory.getLogger(Anyue.class);


    private Site site = Site.me().setRetryTimes(3).setSleepTime(0).setTimeOut(3000);

    //用来存储cookie信息
    private Map<String, String> cookies = new HashMap<>();

    @Override
    public void process(Page page) {
        //获取网页信息
        page.putField("anyue", page.getRawText());

        logger.info("information = " + page.getRawText());
    }

    //使用 selenium 来模拟用户的登录获取cookie信息
    public void login()
    {
//        System.setProperty("webdriver.chrome.driver", "D:\\soft\\chromedriver-win64\\chromedriver.exe");
//        // 忽略证书错误
//        ChromeOptions options = new ChromeOptions();
//        options.setAcceptInsecureCerts(true); // 自动接受不安全证书
//        options.addArguments("--ignore-certificate-errors"); // 忽略所有证书错误

        WebDriver driver = webDriverPool.getSigle() ;
        driver.get("https://192.168.0.223:1443/#/");


//        WebElement  detailutton =  new WebDriverWait(driver, 3).until(browser -> browser.findElement(By.id("details-button")));
//        detailutton.click();
//
//        WebElement element2 =  new WebDriverWait(driver, 3).until(browser -> browser.findElement(By.xpath("/html/body/div/div[3]/p[2]/a")));
//        element2.click();
//
        WebElement element = driver.findElement(By.xpath("/html/body/div[1]/div/div[1]/form/div[1]/div/div/div/input"));
        element.clear();

        //在******中填你的用户名
        element.sendKeys("liwu");
        WebElement login_password = driver.findElement(By.xpath("/html/body/div[1]/div/div[1]/form/div[2]/div/div[1]/div/input"));
        login_password.clear();
        login_password.sendKeys("123456");

        //模拟点击登录按钮
        driver.findElement(By.xpath("/html/body/div[1]/div/div[1]/form/button")).click();

        ThreadUtil.sleep(5000);
        //获取cookie信息
//        driver.close();
        webDriverPool.returnToPool( driver);
        try {
            CommonUtils.saveHomeCookies(driver.manage().getCookies());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    @Override
    public Site getSite() { 

        //将获取到的cookie信息添加到webmagic中
        if(cookies ==  null || cookies.isEmpty()){
            try {
                cookies =   CommonUtils.getHomeCookies();
            } catch (IOException e) {
                throw new RuntimeException(e);
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            } catch (NullCookiesException e) {
                throw new RuntimeException(e);
            }
        }
        String accesskey = "";

        for (String key : cookies.keySet()) {
            if(key.equals("accessKey")){
                accesskey = cookies.get(key);
            }
        }

        site.addHeader("accessKey",accesskey);
        return site.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1");           
    }

    public static void main(String[] args){
        Anyue miai = new Anyue();

        //调用selenium，进行模拟登录
        miai.login();
        Spider.create(miai)
                .setDownloader(new HttpClientDownloader())
        .addUrl("https://192.168.0.223:1443/api/ebd-masterdata/org/getOrgList")
        .run();
    }
}
